package com.guohengspace.mq.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.guohengspace.mq.common.ResponseResult;
import com.guohengspace.mq.model.bo.EipConfigBo;
import com.guohengspace.mq.model.query.EipBatchCreateParam;
import com.guohengspace.mq.service.EipService;
import com.guohengspace.mq.utils.EipConfig;
import com.guohengspace.mq.utils.EipUtil;
import com.guohengspace.mq.utils.IPAddressRangeParser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.net.util.IPAddressUtil;

import java.util.*;

@Slf4j
@Service
public class EipServiceImpl implements EipService {
    private static final Logger logger = LoggerFactory.getLogger(EipServiceImpl.class);
    //static MqUtil mqUtil = new MqUtil();
    @Autowired
    EipUtil eipUtil;

    @Autowired
    EipConfig eipConfig;

    /**
     * 批量添加弹性IP
     *
     * @param eipBatchCreateParam
     * @return
     */
    @Override
    public ResponseResult batchCreate(EipBatchCreateParam eipBatchCreateParam) {
        logger.info("eipBatchCreateParam:" + JSONObject.toJSON(eipBatchCreateParam));
        String ipListStr = eipBatchCreateParam.getIpAddress();
        String inputType = eipBatchCreateParam.getInputType();
        List<String> ipList;
        if (inputType.equals("1")) {
            String[] ipArray = ipListStr.split(",");
            ipList = Arrays.asList(ipArray);
        }else {
            try {
                ipList = IPAddressRangeParser.ipRangeParse(ipListStr);
            }catch (Exception e) {
                logger.error("ipListStr: " + ipListStr + " invalid");
                return ResponseResult.nok(e.getMessage());
            }
        }

        List<String> results = new ArrayList<>();

        for (String ipAddress : ipList) {
            results.add(syncCreateEip(ipAddress, eipBatchCreateParam));
        }

        return ResponseResult.ok(results);
    }

    /**
     * 单次创建弹性IP
     * @param ipAddress 服务IP
     * @param eipBatchCreateParam 创建参数
     * @return 创建结果
     */
    private String syncCreateEip(String  ipAddress, EipBatchCreateParam eipBatchCreateParam) {
        boolean iPv4LiteralAddress = IPAddressUtil.isIPv4LiteralAddress(ipAddress);
        if (!iPv4LiteralAddress) {
            logger.error("name: {}, ipAddress: {} invalid", eipBatchCreateParam.getName(), ipAddress);
            return String.format("ip: %s invalid, eip: failed", ipAddress);
        }

        Map<String, String> paras = getSingleEipCreateParamMap(ipAddress, eipBatchCreateParam);
        String name = paras.get("Name");
        //ResponseResult result = eipUtil.CallEIPAliYunASCM("Vpc", "AllocateEipAddressPro", eipBatchCreateParam.getDepartmentId(), eipBatchCreateParam.getResourceGroupId(), eipBatchCreateParam.getRegionId(), paras);
        ResponseResult result = eipUtil.CallEIPAliYunASCM("Vpc", "AllocateEipAddressPro", eipBatchCreateParam,paras);
        Object data = result.getData();
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(data);
        if (result.getCode() != 0) {
            logger.error("name: {}, ipAddress: {}, code not succeed", name, ipAddress);
            //return String.format("ip: %s, eip: failed", ipAddress);
            return String.format("ip: %s, eipfailed: %s", ipAddress,result.getMessage());
//            return new AsyncResult<>(rs);
        }

        // int asapiSuccessCode = Integer.parseInt(jsonObject.getString("asapiSuccess"));
        String asapiSuccessCode = jsonObject.getString("asapiSuccess");
        if (!asapiSuccessCode.equals("true")) {
            logger.error("name: {}, ipAddress: {}, failed response: {}", name, ipAddress, data);
            return String.format("ip: %s, eipfailed: %s", ipAddress,jsonObject.getString("suggestion"));
//            return new AsyncResult<>(rs);
        }

        String allocationId = jsonObject.getString("AllocationId");
        String eipAddress = jsonObject.getString("EipAddress");
        logger.info("name: {}, ipAddress: {}, allocationId: {}, eipAddress: {}", name, ipAddress, allocationId, eipAddress);
        return String.format("ip: %s, eip: %s", ipAddress, eipAddress);
    }

    private static Map<String, String> getSingleEipCreateParamMap(String ipAddress, EipBatchCreateParam eipBatchCreateParam) {
        Map<String, String> paras = new TreeMap<String, String>();
        paras.put("Name", eipBatchCreateParam.getName() + "-" + ipAddress);
        paras.put("IpAddress", ipAddress);
        paras.put("Bandwidth", eipBatchCreateParam.getBandWidth());
        paras.put("Department", eipBatchCreateParam.getDepartmentId());
        paras.put("ResourceGroup", eipBatchCreateParam.getResourceGroupId());
        paras.put("_Count", "1");
        paras.put("ISP", eipBatchCreateParam.getIsp());
        paras.put("Netmode", eipBatchCreateParam.getNetMode());
        return paras;
    }

    /**
     * 批量添加弹性IP
     *
     * @return
     */
    @Override
    public ResponseResult config() {
        EipConfigBo eipConfigBo = new EipConfigBo();
        eipConfigBo.setDepartments(eipConfig.getDepartments());
        eipConfigBo.setResourceGroups(eipConfig.getResourceGroups());
        eipConfigBo.setRegions(eipConfig.getRegions());
        eipConfigBo.setIsps(eipConfig.getIsps());
        eipConfigBo.setNetModes(eipConfig.getNetModes());
        JSONObject object = (JSONObject) JSONObject.toJSON(eipConfigBo);
        return ResponseResult.ok(object);
    }
}
